import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置为中文
plt.rcParams['axes.unicode_minus'] = False
def load_data():
    df = pd.read_csv('files/The Martian_reviews2.0.csv')
    df['Time'] = pd.to_datetime(df['Time'])
    df['Sentiment'] = df['Sentiment'].astype('category')
    df.set_index('Time', inplace=True)
    return df

def plot_reviews(df):
    daily_counts = df.resample('D').size()
    weekly_counts = df.resample('W').size()
    monthly_counts = df.resample('ME').size()

    start_date = '2015-11-01'
    end_date = '2016-03-01'

    fig, axes = plt.subplots(3, 1, figsize=(10, 12))
    daily_counts[start_date:end_date].plot(ax=axes[0], title='Daily Review Counts', color='b', marker='o')
    weekly_counts[start_date:end_date].plot(ax=axes[1], title='Weekly Review Counts', color='g', marker='o')
    monthly_counts[start_date:end_date].plot(ax=axes[2], title='Monthly Review Counts', color='r', marker='o')
    for ax in axes:
        ax.set_ylabel('Count')
    plt.tight_layout()
    return fig


def plot_sentiments(df):
    daily_sentiments = df.groupby([pd.Grouper(freq='D'), 'Sentiment']).size().unstack(fill_value=0)
    weekly_sentiments = df.groupby([pd.Grouper(freq='W'), 'Sentiment']).size().unstack(fill_value=0)
    monthly_sentiments = df.groupby([pd.Grouper(freq='M'), 'Sentiment']).size().unstack(fill_value=0)

    start_date = '2015-11-01'
    end_date = '2016-03-01'

    fig, axes = plt.subplots(3, 1, figsize=(10, 12))


    for sentiment in daily_sentiments.columns:
        axes[0].plot(daily_sentiments[start_date:end_date].index, daily_sentiments[start_date:end_date][sentiment],
                     marker='o', label=sentiment)
    axes[0].set_title('Daily Sentiment Trends')
    axes[0].set_ylabel('Count')
    axes[0].legend()

    for sentiment in weekly_sentiments.columns:
        axes[1].plot(weekly_sentiments[start_date:end_date].index, weekly_sentiments[start_date:end_date][sentiment],
                     marker='o', label=sentiment)
    axes[1].set_title('Weekly Sentiment Trends')
    axes[1].set_ylabel('Count')
    axes[1].legend()

    for sentiment in monthly_sentiments.columns:
        axes[2].plot(monthly_sentiments[start_date:end_date].index, monthly_sentiments[start_date:end_date][sentiment],
                     marker='o', label=sentiment)
    axes[2].set_title('Monthly Sentiment Trends')
    axes[2].set_ylabel('Count')
    axes[2].legend()

    plt.tight_layout()
    return fig


def main():
    st.title('《火星救援》影评分析')

    df = load_data()

    st.header('评论数量随时间转移情况')
    fig = plot_reviews(df)
    st.pyplot(fig)

    st.header('评论类型随时间转移情况')
    sentiment_fig = plot_sentiments(df)
    st.pyplot(sentiment_fig)

if __name__ == "__main__":
    main()
